package com.lihua.newideas.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.lihua.newideas.pojo.MyUser;
import com.lihua.newideas.service.PhoneCodeService;
import com.lihua.newideas.service.impl.MyUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//登录
@Controller
public class LoginController {

    @Autowired
    private MyUserServiceImpl userServiceImple;

    @Autowired
    private PhoneCodeService phoneCodeService;


    //注册
    @PostMapping("/regSubmit")
    @ResponseBody
    public  String regSubmit(MyUser user){
        System.out.println(user.toString());
        if(!user.getUserName().equals("")&&!user.getUserName().equals("")){
            String resultCode = phoneCodeService.isPhoneCode(user.getUserName(), user.getCode());
            System.out.println(resultCode);
            if (resultCode.equals("1")){
                if (userServiceImple.insertUser(user)!=null){
                    return "注册成功";
                }else {
                    return "用户已存在";
                }
            }else if (resultCode.equals("0")){
                return "验证码过期";
            }else {
                return resultCode;
            }

        }else {
            return "账号密码不能为空";
        }
    }
    //修改密码
    @PostMapping("/updatePassWord")
    @ResponseBody
    public String updatePassWord(MyUser user){
        System.out.println(user.toString());
        String s = userServiceImple.updateUserByUserName(user.getPassWord(), user.getUserName(), user.getCode());
        System.out.println(s);
        if (s.equals("0")){
            return "验码过期";
        }else {
            return s;
        }

    }
    /**
     *获取验证码
     * */
    @RequestMapping("/sendCode/{phone}")
    @SentinelResource(value = "sendCode-consume",defaultFallback = "defaultFallback")
    @ResponseBody
    public String sendCode(@PathVariable("phone") String phone){
        String b = phoneCodeService.sendCode(phone);
        return b;
    }

    /**
     * 返回值类型必须与原函数返回值类型一致；
     * 方法参数列表需要为空，或者可以额外多一个 Throwable 类型的参数用于接收对应的异常。
     * 为了解决代码膨胀，我们给一个默认的降级方法
     * */
    public static String defaultFallback(Throwable e){
        return e.getMessage();
    }

}
